<template>
  <page-wrap stay-still hide-tab title="填写总结">
    <view class="summary">
      <view class="summary-header">
        <text class="title">服务名称：</text>
        <text class="value">{{ serviceName }}</text>
      </view>
      <view class="summary-form-wrap">
        <u-form
          class="summary-form"
          label-position="top"
          ref="uForm"
          :model="form"
          :error-type="['message']"
        >
          <block v-for="(item, index) in formList" :key="index">
            <view
              class="form-item-wrap"
              v-if="!item.baseOn || form[item.baseOn.prop] == item.baseOn.value"
              @click.capture="handleSelect(item, index)"
            >
              <u-form-item
                :class="{ pick: item.comp }"
                :label="item.label"
                :prop="item.prop"
              >
                <u-input
                  class="form-input"
                  v-model="form[item.prop]"
                  :disabled="!!item.comp"
                  :type="item.type"
                  :placeholder="item.inputPlaceholder"
                  :clearable="false"
                  @blur="handleSaveItem(item)"
                  maxlength="1000"
                />
                <!-- 下拉选择 -->
                <u-select
                  class="form-select"
                  v-model="item.show"
                  :list="item.data"
                  v-if="item.comp === 'select'"
                  @confirm="handleConfirm($event, item)"
                ></u-select>
                <u-popup
                  v-if="item.comp === 'pop'"
                  v-model="item.show"
                  mode="bottom"
                  height="260px"
                  :closeable="true"
                >
                  <view class="question-wrapper">
                    <view class="pop-title">请选择问题类型</view>
                    <u-checkbox-group
                      active-color="#f75a3e"
                      @change="handleChangeQuestionType"
                    >
                      <u-checkbox
                        v-for="item in questionTypeOptions"
                        :key="item.value"
                        :name="item.value"
                        v-model="item.checked"
                        >{{ item.label }}</u-checkbox
                      >
                    </u-checkbox-group>
                  </view>
                </u-popup>
              </u-form-item>
            </view>
          </block>
        </u-form>
      </view>
      <view class="operate-bar">
        <u-button
          class="save-btn"
          type="default"
          shape="circle"
          @click="handleSave"
          >返回</u-button
        >
        <u-button
          class="save-btn"
          type="primary"
          shape="circle"
          :loading="publishLoading"
          @click="handlePublish"
          >发布</u-button
        >
      </view>
    </view>
  </page-wrap>
</template>

<script>
import {
  editServiceSummary,
  pubServiceSummary,
  viewServiceSummary,
} from "@/api/modules/career";
import RegionFilter from "@/components/RegionFilter";
import ShareMixin from "@/mixins/share";
export default {
  mixins: [ShareMixin],
  components: {
    RegionFilter,
  },
  data() {
    return {
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      userInfo: {},
      form: {
        username: "",
        userSex: "男",
        userAge: "",
        questionType: "",
        questionDetail: "",
        solution: "",
      },
      formList: [
        {
          label: "用户姓名",
          prop: "username",
          inputPlaceholder: "请输入用户姓名",
          type: "text",
          dataType: 17,
          orderNum: 1,
        },
        {
          label: "用户年龄",
          prop: "userAge",
          inputPlaceholder: "请输入用户年龄",
          type: "text",
          dataType: 19,
          orderNum: 2,
        },
        {
          label: "用户性别",
          prop: "userSex",
          inputPlaceholder: "请选择用户性别",
          comp: "select",
          dataType: 18,
          orderNum: 3,
          data: [
            {
              label: "男",
              value: "男",
            },
            {
              label: "女",
              value: "女",
            },
          ],
          show: false,
        },
        {
          label: "问题类型",
          prop: "questionType",
          inputPlaceholder: "请选择问题类型",
          comp: "pop",
          dataType: 1,
          orderNum: 4,
          show: false,
        },
        {
          label: "问题详情",
          prop: "questionDetail",
          inputPlaceholder: "请输入问题详情",
          type: "textarea",
          dataType: 2,
          orderNum: 5,
        },
        {
          label: "解决方案",
          prop: "solution",
          inputPlaceholder: "请输入解决方案",
          type: "textarea",
          dataType: 3,
          orderNum: 6,
        },
      ],
      questionTypeOptions: [
        { checked: false, value: "职业规划", label: "职业规划" },
        { checked: false, value: "简历精修", label: "简历精修" },
        { checked: false, value: "投递指导", label: "投递指导" },
        { checked: false, value: "面试辅导", label: "面试辅导" },
        { checked: false, value: "薪酬谈判", label: "薪酬谈判" },
        { checked: false, value: "风险规避", label: "风险规避" },
        { checked: false, value: "Offer筛选", label: "Offer筛选" },
      ],
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: ["change", "blur"],
          },
        ],
        userSex: [
          {
            required: true,
            message: "请输入用户姓名",
            trigger: ["change", "blur"],
          },
        ],
        userAge: [
          {
            required: true,
            message: "请输用户年龄",
            trigger: ["change", "blur"],
          },
        ],
        questionType: [
          {
            required: true,
            message: "请选择问题类型",
            trigger: ["change", "blur"],
          },
        ],
        questionDetail: [
          {
            required: true,
            message: "请输入问题详情",
            trigger: ["change", "blur"],
          },
        ],
        solution: [
          {
            required: true,
            message: "请输入解决方案",
            trigger: ["change", "blur"],
          },
        ],
      },
      publishLoading: false,
      serviceName: "",
      serviceRecordId: "",
      serviceId: "",
      id: "",
      keyIdMap: new Map(),
    };
  },
  watch: {
    userInfo: {
      handler(val) {
        this.form = {
          username: val.username,
          userSex: val.userSex,
          userAge: val.userAge,
          questionDetail: val.questionDetail,
          solution: val.solution,
        };
      },
      immediate: true,
    },
  },
  onShow() {},
  onLoad(opt) {
    this.serviceName = opt.serviceName || "在线咨询";
    this.serviceId = opt.serviceId || "";
    this.serviceRecordId = opt.serviceRecordId || "";
  },
  mounted() {
    this.viewServiceSummaryFn();
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    handleChangeQuestionType(val) {
      this.form.questionType = val.join(",");
      const params = {
        serviceRecordId: this.serviceRecordId,
        serviceId: this.serviceId,
        dataType: 1,
        content: this.form.questionType,
        orderNum: 4,
      };
      if (this.keyIdMap.get(1)) {
        params.id = this.keyIdMap.get(1);
      }
      this.editServiceSummaryFn(params);
    },
    handleSaveItem(item) {
      const params = {
        serviceRecordId: this.serviceRecordId,
        serviceId: this.serviceId,
        dataType: item.dataType,
        content: this.form[item.prop],
        orderNum: item.orderNum,
      };
      if (this.keyIdMap.get(item.dataType)) {
        params.id = this.keyIdMap.get(item.dataType);
      }
      this.editServiceSummaryFn(params);
    },
    editServiceSummaryFn(params) {
      editServiceSummary(params).then((res) => {
        if (res.code !== 200) {
          uni.showToast({ icon: "none", title: res.status_desc });
        } else {
          if (!this.keyIdMap.get(params.dataType)) {
            // 编辑过后如果没有主键id的话就保存起来
            this.keyIdMap.set(params.dataType, res.data.id);
          }
          // uni.showToast({ icon: "none", title: "已保存当前更改" });
        }
      });
    },
    viewServiceSummaryFn() {
      const params = {
        serviceRecordId: this.serviceRecordId,
        serviceId: this.serviceId,
      };
      viewServiceSummary(params).then((res) => {
        if (res.code == 200 && Array.isArray(res.data) && res.data.length) {
          res.data.forEach((item) => {
            this.keyIdMap.set(item.dataType, item.id); // 保存每一项的主键id，用作编辑
            if (item.dataType == 1) {
              this.form.questionType = item.content;
            }
            if (item.dataType == 2) {
              this.form.questionDetail = item.content;
            }
            if (item.dataType == 3) {
              this.form.solution = item.content;
            }
            if (item.dataType == 17) {
              this.form.username = item.content;
            }
            if (item.dataType == 18) {
              this.form.userSex = item.content;
            }
            if (item.dataType == 19) {
              this.form.userAge = item.content;
            }
          });
        }
      });
    },
    handlePublish() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.publishLoading = true;
          const params = {
            serviceRecordId: this.serviceRecordId,
            serviceId: this.serviceId,
          };
          pubServiceSummary(params)
            .then((res) => {
              if (res.code == 200) {
                uni.showToast({ icon: "none", title: "发布成功！" });
                this.handleSave();
              }
            })
            .finally(() => {
              this.publishLoading = false;
            });
        } else {
          uni.showToast({ icon: "none", title: "请完善信息后再发布！" });
        }
      });
    },
    handleSave() {
      uni.redirectTo({
        url: `/pagesSub/userCenter/serviceRecord/index`,
      });
    },
    handleShow(item) {
      this.$set(item, "show", false);
    },
    handleSelect(item) {
      if (item.comp) {
        this.$set(item, "show", true);
      }
    },
    handleConfirm(e, item) {
      if (Array.isArray(e)) {
        this.$set(this.form, item.prop, e[0].label);
        if (item.propVal) {
          this.$set(this.form, item.propVal, e[0].value);
        }
      } else {
        let time = `${e.year}-${e.month}-${e.day}`;
        this.$set(this.form, item.prop, time);
      }
      setTimeout(() => {
        this.$refs.uForm.validate();
        const params = {
          serviceRecordId: this.serviceRecordId,
          serviceId: this.serviceId,
          dataType: item.dataType,
          content: this.form[item.prop],
          orderNum: item.orderNum,
        };
        if (this.keyIdMap.get(item.dataType)) {
          params.id = this.keyIdMap.get(item.dataType);
        }
        this.editServiceSummaryFn(params);
      }, 0);
    },
  },
};
</script>

<style lang="scss" scoped>
.summary {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 32rpx 32rpx 36rpx;
  box-sizing: border-box;
  position: relative;
  &-header {
    font-size: 32rpx;
    padding: 0 0 24rpx 32rpx;
    color: #333;
    font-weight: 600;
    .title {
      margin-right: 12rpx;
      color: #666;
    }
    .value {
      color: #555;
    }
  }
  .summary-form-wrap {
    flex-grow: 1;
    background: #fff;
    padding: 32rpx 0 60rpx 0;
    border-radius: 16rpx;
    ::v-deep .u-form {
      padding: 0 32rpx;
      background: $uni-bg-color;
      border-radius: 24rpx;
      .u-form-item {
        .btn-group {
          padding: 0 24rpx;
          line-height: 102rpx;
          .cancel,
          .confirm {
            padding: 0 16rpx;
          }
        }
      }
    }
  }
  .operate-bar {
    display: flex;
    justify-content: space-evenly;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 99;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    .save-btn {
      flex-shrink: 0;
      margin: 0rpx 0 10rpx;
      width: 40%;
    }
  }
  .question-wrapper {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 32rpx;
    .pop-title {
      font-size: 28rpx;
      text-align: center;
      padding: 0 0 32rpx 0;
    }
  }
}
::v-deep .u-input__textarea {
  min-height: 80rpx !important;
}
::v-deep .u-input input {
  font-size: 28rpx !important;
}
::v-deep .u-btn--default {
  color: #fff !important;
  border-color: #c0c4cc;
  background-color: #c0c4cc !important;
}
</style>
